package com.peng.leetcode.other;

/**
 * MergeTwoLists
 *
 * @author: lupeng6
 * @create: 2020/11/14 23:02
 */
public class MergeTwoLists {


    public static void main(String[] args) {

        ListNode l1 = new ListNode(1, new ListNode(4, new ListNode(5, null)));
        ListNode l2 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(6, null))));


        ListNode l3 = new MergeTwoLists().mergeTwoLists2(l1, l2);
        String s= "";
        ListNode next = l3;
        while (next != null) {
            s += "->" + next.val;
            next = next.next;
        }
        System.out.println(s);
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }

    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        ListNode temp = new ListNode(-1, null);

        ListNode start = temp;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                start.next = l1;
                l1 = l1.next;
            } else {
                start.next = l2;
                l2 = l2.next;
            }
            start = start.next;
        }

        start.next = l1 == null ? l2 : l1;
        return temp.next;
    }

}


class ListNode {
    int val;
    ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

}
